<?php

class User_Controller extends IW_Controller
{
	function index()
	{
		$this->redirect($this->url('user', 'signin'));
	}

	function signin()
	{
		if (!isset($_POST['loginUser']) and !isset($_POST['passwordUser'])){
			$this->view->assign('incorrectUserPass', false);
			$this->view->display('signin_view');
		} else if(!isset($_POST['loginUser'])) {
			$emptyFields[] = 'loginUser';
		} else if(!isset($_POST['passwordUser'])) {
			$emptyFields[] = 'passwordUser';
		} else {
			$this->load->model('User_Model', 'userModel');
			$userModel = $this->userModel->find($_POST['loginUser']);
			if($userModel and $userModel->isValidPassword($_POST['passwordUser'])) {
				$_SESSION['userId'] = $userModel->getId();
				$_SESSION['userName'] = $userModel->getName();
				$this->redirect($this->url('index'));
			} else {
				$this->view->assign('incorrectUserPass', true);
				
				//$this->layout->display();
				
				$this->view->display('signin_view');
			}
		}
				
	}
	
	function signout() 
	{
		if(isset($_SESSION['userId'])) {
			unset($_SESSION['userId']);
		}
		if(isset($_SESSION['userName'])) {
			unset($_SESSION['userName']);
		}
		session_destroy();
		$this->redirect($this->url('index'));
	}
	
	
	function profile()
	{
		$this->load->model('User_Model', 'userModel');
		
		if($uid = $this->paramIndex(0)) {
			$userModel = $this->userModel->find($uid);
		} else if(isset($_SESSION['userId'])) {
			$userModel = $this->userModel->find($_SESSION['userId']);
		} else {
			die('Zaloguj się, by oglądać swój profil');
		}
		
		if($userModel) {
			$this->view->assign('name', $userModel->getName());
			$this->view->assign('email', $userModel->getEmail());
			$this->view->display('profile_view');
		} else {
			die('Użytkownik o podanym id nie istnieje');
		}
		
		
	}

}
